//task_material.js
const util = require("../../utils/util.js");
var tDate = require("../../utils/date.js");
const app = getApp()

Page({
  data: {
    order_id: '',
    // 任务类型 未完成：32；已完成：33
    taskStatus: "",
    selectedTask_type: "准备物料",
    // 任务时间
    taskTime: "",
    // 住宅位置
    taskAddress: "",
    // 准备物料
    materialPreparation: "",
    // 下单时间
    inputedInstallTime: "",
    // 滤网更换日期
    installTime: "0",
    // 输入物料需求
    materialNotes: "",

    selecteDate: "",
    selectTime: "",
    dateValue: [0, 0],
    dateValues: [0, 0],
    selectPicker: false,

    // 房间物料展示数组
    house_materiel_array: []
  },
  onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      order_id: options.id,
      taskTime: options.time,
      taskAddress: options.address,
      taskStatus: options.taskStatus
    })

    this.refreshNewData();
    this.$wuxToast = app.wux(this).$wuxToast;

    var that = this;
    tDate.init(that);
    var timeData = that.data.timeData;
    var dates = [];
    var times = [];

    for (let i = 0; i < timeData.length; i++) {
      dates.push(timeData[i].name);
    }
    console.log('日期完成');
    for (let i = 0; i < timeData[0].time.length; i++) {
      times.push(timeData[0].time[i].name)
    }

    that.setData({
      dates: dates,
      times: times,
      date: timeData[0].name,
      time: timeData[0].time[0].name,
      selecteDate: timeData[0].name,
      selectTime: timeData[0].time[0].name
    })
  },
  // 日期更改
  bindDateChange: function (e) {
    var val = e.detail.value
    var t = this.data.dateValues;
    var timeData = this.data.timeData;

    if (val[0] != t[0]) {
      const times = [];
      for (let i = 0; i < timeData[val[0]].time.length; i++) {
        times.push(timeData[val[0]].time[i].name)
      }
      this.setData({
        selecteDate: this.data.dates[val[0]],
        times: times,
        dateValues: val,
        dateValue: [val[0], 0]
      })
      return;
    }
    if (val[1] != t[1]) {
      this.setData({
        selectTime: this.data.times[val[1]],
        dateValues: val,
        dateValue: [val[0], val[1]]
      })
      return;
    }
  },
  // 打开日期弹窗
  openDate: function () {
    this.setData({
      selectPicker: true
    })
  },
  // 取消
  cancleSelected: function () {
    this.setData({
      selectPicker: false,
      selecteDate: this.data.date,
      selectTime: this.data.time
    })
  },
  // 确定
  confirmDate: function (e) {
    var newInstallTime = this.data.selecteDate + " " + this.data.selectTime;
    this.setData({
      installTime: newInstallTime,
      date: this.data.selecteDate,
      time: this.data.selectTime,
      selectPicker: false
    })
  },

  //输入勘测备注
  inputMaterialNotes: function (e) {
    this.setData({
      materialNotes: e.detail.value
    })
  },
  // 物料信息输入框
  materiel_bindinput: function (e) {
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    var houseIndex = e.currentTarget.dataset.houseindex;
    console.log("物料信息：index ===" + index + "; houseIndex==" + houseIndex);

    this.data.house_materiel_array[houseIndex].materielArray[index].materielPrice = value;

    // 修改全局变量
    this.setData({
      house_materiel_array: this.data.house_materiel_array
    })

  },
  // 提交表单按钮
  submitInfo: function () {
    var installStr = this.data.installTime;
    var materialNotesStr = this.data.materialNotes;
    var taskStatus = this.data.taskStatus;

    console.log("时间：" + installStr);
    console.log("备注：" + materialNotesStr);
    console.log("11111+adminUserViewId:" + app.globalData.adminUserViewId);
    console.log("111111+token:" + app.globalData.token);

    //刷新数据
    //加载提示框
    util.showLoading();
    var that = this;
    var pages = getCurrentPages()
    // var prevPage = pages[pages.length-1]  //当前界面
    var prevPage = pages[pages.length - 2]  //上一个页面
    
    var urlString = app.globalData.BaseURL + '/api/task/addMatriReport';
    var dataSource;
    if (taskStatus === "32") {
      dataSource = util.json2Form({
        taskId: that.data.order_id,
        orderTime: installStr,
        remark: materialNotesStr
      });
    } else {
      dataSource = util.json2Form({
        taskId: that.data.order_id,
        orderEndTime: installStr,
        remark: materialNotesStr
      });
    }

    wx.request({
      method: "POST",
      url: urlString,
      data: dataSource,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'adminUserViewId': app.globalData.adminUserViewId,
        'token': app.globalData.token
      },
      success: function (res) {
        util.hideToast();
        console.log("data====="+res.data);
        var code = res.data.code;
        console.log("code====="+code);
        // code = 300;
        if (code === 200) {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: '上传成功',
            success: () => console.log('提交成功')
          });
          // 更改前一页面列表页的refreshLish属性，让其出现时刷新页面
          prevPage.setData({
            refreshLish: "true"
          });
          setTimeout(function () {
            wx.navigateBack({});
          }, 1000);
        } else {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: res.data.msg,
            success: () => console.log('上传失败，请重新提交。')
          });
        }
      },
      fail: function () {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '网络错误，请稍后重试。',
          success: () => console.log('网络错误，请稍后重试。')
        })
      }, complete: function () {
        util.hideToast();
      }
    })
  },
  // 任务失败跳转
  taskFailedAction: function () {
    var that = this;
    wx.navigateTo({
        url: '/pages/task_failed/task_failed' + '?id=' + that.data.order_id + '&time=' + that.data.taskTime + '&address=' + that.data.taskAddress + '&task_type=' + that.data.selectedTask_type
      })
  },
  //刷新数据
  refreshNewData: function () {
    //加载提示框
    util.showLoading();
    var that = this;
    var urlStr = '/api/task/' + this.data.order_id;
    var parameters = "";
    console.log("parameters = " + parameters);
    util.request(urlStr, parameters, function (res) {
      console.log("data===" + res.data);
      util.hideToast();
      var materialPreStr = res.data.data.materielReqment;
      var timeStr = res.data.data.time;
      that.setData({
        inputedInstallTime: timeStr,
        house_materiel_array: materialPreStr
      });

      var startTime = res.data.data.task.startTime;
      if (startTime == "" || startTime == undefined) {
        // 未开始任务，提示先开始任务
        wx.showModal({
          title: '该任务暂未开始',
          content: '请返回首页开始任务，再提交任务信息',
          cancelText: '暂不开始',
          confirmText: '立即返回',
          success: function (res) {
            if (res.confirm) {
              console.log("确认返回首页");
              wx.navigateBack({})
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  }, complete: function() {
    util.hideToast();
  }
})




